#!/usr/bin/env python3
#-*- encoding:utf-8 -*-

import argparse
import gi
import os
import sys
import subprocess
import time
import threading

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from gi.repository import GLib

parser = None
swtitle = 'ADBme'
swver = '1.0'
win = None

def shellexec(strcmd):
    try:
        print("正在运行指令：" + strcmd)
        process = subprocess.Popen(strcmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) #, cwd=os.environ['ZZSWMGR_WORK_DIR'], env={'ZZSWMGR_WORK_DIR':os.environ['ZZSWMGR_WORK_DIR']})
        # process.stdin.close()
        # process.stdout.close()
        process.wait()
        strout = process.stdout.read().decode("utf8")
        # print(strout)
        return process.returncode
    except Exception as e:
        print("" + e)
        return -1



class WorkerAppend(threading.Thread):
    def __init__(self, window, strMode, srcpath, txtpth1, txtpth2, dstpath):
            threading.Thread.__init__(self)
            self.window = window
            self.strMode = strMode
            self.srcpath = srcpath
            self.txtpth1 = txtpth1
            self.txtpth2 = txtpth2
            self.dstpath = dstpath

    def run(self):
            rltcode=0
            rltmesg=""

            print(self.srcpath)
            print(self.txtpth1)
            print(self.txtpth2)
            print(self.dstpath)

            if self.strMode == "1to4":
                rltcode, rltmesg = self.action_1to4()
            elif self.strMode == "23to4":
                rltcode, rltmesg = self.action_23to4()
            elif self.strMode == "1to2":
                rltcode, rltmesg = self.action_1to2()
            elif self.strMode == "4to3":
                rltcode, rltmesg = self.action_4to3()

            GLib.idle_add(self.window.onComplete, rltcode, rltmesg)

            # GLib.idle_add(self.window.setmesg, "请选择待合并的文件(文件1)")

            # if self.dstpath == "":
            #     GLib.idle_add(self.window.setmesg, "请选择目标文件(文件4)")
            #     return

            # if os.path.exists(dstpath):
            #     ;
            # else:
            #     fp = open(dstpath, 'w')
            #     fp.write(text)
            # GLib.idle_add(self.window.onComplete, rltcode, rltmesg)

class DialogPairCode(Gtk.Dialog):
    resultstr = ""

    def __init__(self, parent):
        super().__init__(title="连接本机ADB通道", transient_for=parent, flags=0)
        self.add_buttons(
            "取消", Gtk.ResponseType.CANCEL, "连接", Gtk.ResponseType.OK
        )

        self.set_default_size(580, 300)
        box = self.get_content_area()
        box.set_border_width(30)


        txtmesg="" + \
            "步骤较繁琐，请按照提示一步步操作!\n" + \
            "\n" + \
            "具体步骤如下：\n" + \
            " 1). 将手机连接到wifi网络，可以是热点网络\n" + \
            " 2). 在手机设置的关于本机界面中，启用手机的 \"开发者选项\"\n" + \
            "     (连点10次设置中的 \"版本号\")\n" + \
            " 3). 在手机上，将虚拟电脑浮窗化运行(不要关闭此对话框)\n" + \
            " 4). 在手机上，打开无线调试界面，查看匹配码和验证端口号\n" + \
            "     (在匹配成功之前，不能关闭手机上弹出的匹配码窗口)\n" + \
            " 5). 在手机上，点击虚拟电脑底部任意按钮，弹出屏幕键盘\n" + \
            "     (输入匹配码和验证端口)\n" + \
            " 6). 匹配完成后，再输入adb连接端口号" + \
            ""

        label = Gtk.Label(label="步骤较繁琐，请按照提示一步步操作!", xalign=0)
        label.set_markup(txtmesg)
        box.add(label)

        label = Gtk.Label(label="sdfsdf", xalign=0)
        box.add(label)

        self.change_font("", 16)
        self.show_all()

    def change_font(self, fontname='', fontsize=16):
        # settings = Gtk.Settings.get_default()
        # settings.set_property(Gtk.Settings.Property.FONT_SIZE, 50)

        settings = Gtk.Settings.get_default()
        settings.set_property("gtk-font-name", f"{fontname} {fontsize}")
        Gtk.StyleContext.invalidate()
        # Gtk.StyleContext.invalidate_all()



    @staticmethod
    def show(win):
        rlt = ""
        dialog = DialogPairCode(win)
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            rlt = dialog.resultstr
        dialog.destroy()
        return rlt

class ADBme(Gtk.Grid):
    def __init__(self, stack):
        super(ADBme,self).__init__()
        self.stack = stack

        rows=0;wcolumn0=30;wcolumn1=60
        # page = Gtk.Label(label="待实现", xalign=0, yalign=0)
        # page = Gtk.Grid()
        page = self
        page.set_border_width(5)
        page.set_column_spacing(10)
        page.set_row_spacing(30)
        stack.add_titled(page, "page_ADBme", "\n常用功能\n")

        txtmesg="" + \
            "　警告：\"开发者选项\" 启用后有被偷录屏幕、恶意安装app等风险\n" + \
            ""

        txtinfo = Gtk.Label(label="", xalign=0)
        txtinfo.set_markup(txtmesg)
        page.attach(txtinfo, 0, rows, 60, 1)
        rows += 1

        self.btnADBConnect = Gtk.Button(label="\n连接本机ADB通道\n")
        self.btnADBConnect.connect("clicked", self.onClick_btnADBConnect)
        idesc = Gtk.Label(label="效果等同运行以下指令：\nadb pair         127.0.0.1:匹配端口   匹配码\nadb connect 127.0.0.1:连接端口\nadb tcpip 1111\nadb connect 127.0.0.1:1111", xalign=0)
        idesc.set_justify(Gtk.Justification.LEFT)
        page.attach(self.btnADBConnect, 0, rows, wcolumn0, 1)
        page.attach_next_to(idesc, self.btnADBConnect, Gtk.PositionType.RIGHT, wcolumn1, 1)
        rows += 1

        self.btnEnableMP = Gtk.Button(label="\n启用 本机多进程保活\n")
        # self.btnEnableMP.connect("clicked", self.on_btnEnableMP_clicked)
        idesc = Gtk.Label(label="效果等同运行以下指令：\nadb shell device_config set_sync_disabled_for_tests \\\n    persistent\nadb shell device_config put activity_manager \\\n    max_phantom_processes 65536", xalign=0)
        idesc.set_justify(Gtk.Justification.LEFT)
        page.attach(self.btnEnableMP, 0, rows, wcolumn0, 1)
        page.attach_next_to(idesc, self.btnEnableMP, Gtk.PositionType.RIGHT, wcolumn1, 1)
        rows += 1

    def onClick_btnADBConnect(self, widget):
        global win
        newaddr = DialogPairCode.show(win)
        # print(newaddr)
        # if(newaddr==""):

class ADBop(Gtk.Grid):
    def __init__(self, stack):
        super(ADBop,self).__init__()
        self.stack = stack

        rows=0;wcolumn0=33;wcolumn1=33;wcolumn2=33
        page = self
        page.set_border_width(5)
        page.set_column_spacing(5)
        page.set_row_spacing(10)
        stack.add_titled(page, "page_ADBop", "\n对连设备\n")

        iname = Gtk.Label(label="请选择设备：", xalign=1.0)
        ictrl = Gtk.ComboBoxText()
        ictrl.append_text("未识别到USB对连设备")
        ictrl.append_text("默认+兼容")
        self.cbDevList = ictrl
        ictrl.connect('changed', self.onComboPreSetChanged)
        self.btnScanDev = Gtk.Button(label="\n刷新\n")
        page.attach(iname, 0, rows, wcolumn0, 1)
        page.attach_next_to(ictrl, iname, Gtk.PositionType.RIGHT, 50, 1)
        page.attach_next_to(self.btnScanDev, ictrl, Gtk.PositionType.RIGHT, 16, 1)
        rows += 1

        iname = Gtk.Label(label="", xalign=1.0)
        self.btnOpenWifiAdb = Gtk.Button(label="\n打开所选设备的wifi-adb通道\n")
        self.btnOpenWifiAdb.connect("clicked", self.on_btnOpenWifiAdb_clicked)
        page.attach(iname, 0, rows, wcolumn0, 1)
        page.attach_next_to(self.btnOpenWifiAdb, iname, Gtk.PositionType.RIGHT, 13, 1)
        rows += 1

        # 最后再做这个动作！
        self.cbDevList.set_active(0)

    def on_btnOpenWifiAdb_clicked(self, widget):
        global win
        try: 
            win.showmessage("保存成功", f"保存成功")
        except Exception as e: 
            win.showmessage("无法保存", f"错误信息：\n{e}")
            return False

    def onComboPreSetChanged(self, combo):
        txt_preset = combo.get_active_text()
        # print("txt_preset: " + txt_preset)
        if txt_preset == "兼容性最好" :
            # print ("__name__" + type(self).__name__)
            self.BOX64_DYNAREC_ALIGNED_ATOMICS.set_active(4)
            self.BOX64_DYNAREC_FASTNAN.set_active(0)
            self.BOX64_DYNAREC_FASTROUND.set_active(0)
            self.BOX64_DYNAREC_SAFEFLAGS.set_active(2)
            self.BOX64_DYNAREC_STRONGMEM.set_active(3)
            self.BOX64_DYNAREC_WAIT.set_active(1)
            self.BOX64_DYNAREC_X87DOUBLE.set_active(1)
            self.BOX64_DYNAREC_CALLRET.set_active(0)
            self.BOX64_IGNOREINT3.set_active(4)
        elif txt_preset == "默认+兼容" :
            self.BOX64_DYNAREC_ALIGNED_ATOMICS.set_active(4)
            self.BOX64_DYNAREC_FASTNAN.set_active(0)
            self.BOX64_DYNAREC_FASTROUND.set_active(4)
            self.BOX64_DYNAREC_SAFEFLAGS.set_active(2)
            self.BOX64_DYNAREC_STRONGMEM.set_active(2)
            self.BOX64_DYNAREC_WAIT.set_active(4)
            self.BOX64_DYNAREC_X87DOUBLE.set_active(4)
            self.BOX64_DYNAREC_CALLRET.set_active(0)
            self.BOX64_IGNOREINT3.set_active(4)
        elif txt_preset == "默认设置" :
            self.BOX64_DYNAREC_ALIGNED_ATOMICS.set_active(4)
            self.BOX64_DYNAREC_FASTNAN.set_active(4)
            self.BOX64_DYNAREC_FASTROUND.set_active(4)
            self.BOX64_DYNAREC_SAFEFLAGS.set_active(4)
            self.BOX64_DYNAREC_STRONGMEM.set_active(4)
            self.BOX64_DYNAREC_WAIT.set_active(4)
            self.BOX64_DYNAREC_X87DOUBLE.set_active(4)
            self.BOX64_DYNAREC_CALLRET.set_active(0)
            self.BOX64_IGNOREINT3.set_active(4)
        elif txt_preset == "性能最高" :
            self.BOX64_DYNAREC_ALIGNED_ATOMICS.set_active(4)
            self.BOX64_DYNAREC_FASTNAN.set_active(4)
            self.BOX64_DYNAREC_FASTROUND.set_active(4)
            self.BOX64_DYNAREC_SAFEFLAGS.set_active(0)
            self.BOX64_DYNAREC_STRONGMEM.set_active(4)
            self.BOX64_DYNAREC_WAIT.set_active(4)
            self.BOX64_DYNAREC_X87DOUBLE.set_active(4)
            self.BOX64_DYNAREC_CALLRET.set_active(0)
            self.BOX64_IGNOREINT3.set_active(4)

class Mainform(Gtk.Window):
    def __init__(self):
        global win
        super(Mainform,self).__init__(title=swtitle)
        self.set_default_size(800, 900)
        self.set_icon_from_file("/exbin/tools/zzswmgr/appicons/android.jpg")
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_border_width(3)
        self.set_name("Mainform")
        win = self

        # self.scroll_window = Gtk.ScrolledWindow()
        # self.add(self.scroll_window)

        self.grid = Gtk.Grid()
        # self.scroll_window.add(self.grid)
        self.grid.set_border_width(20)
        self.grid.set_column_spacing(5)
        self.grid.set_row_spacing(10)
        self.add(self.grid)

        txtReadme="" + \
            "　软件功能如下：(欢迎加群交流：740164688)\n" + \
            "======================================================================\n" + \
            "1). 可打开安卓对 \"多进程应用\" 的 \"<b>多进程保活</b>\" 功能\n" + \
            "　　即调高单个应用最多能打开的进程数量上限\n" + \
            "\n" + \
            "2). 可实现 \"<b>adb回连</b>\"\n" + \
            "　　不需要借助电脑使用adb控制安卓设备，走wifi-adb通道 (默认端口: 1111)\n" + \
            "\n" + \
            "3). 可打开 \"USB对连\" 设备的 \"<b>wifi-adb通道</b>\"\n" + \
            "　　当前设备需要先启用OTG功能，并使用usb数据线连接好其它手机\n" + \
            "\n" + \
            "======================================================================\n" + \
            ""

        rows = 0
        self.lblinfo = Gtk.Label(label="", xalign=0, yalign=0.5)
        self.lblinfo.set_markup(txtReadme)
        self.lblinfo.get_style_context().add_class("lblinfo")
        self.grid.attach(self.lblinfo, 0, rows, 1, 1)
        rows += 1

        self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        self.grid.attach(self.hbox, 0, rows, 1, 1)
        rows += 1


        stack = Gtk.Stack()
        stack.set_transition_type(Gtk.StackTransitionType.SLIDE_UP_DOWN)
        stack.set_transition_duration(1000)
        stack.set_hexpand(True) # 自动铺满可用区域
        stack.set_vexpand(True)

        ADBme(stack)
        ADBop(stack)


        # label = Gtk.Label()
        # label.set_markup("<big>A fancy label</big>")
        # stack.add_titled(label, "label", "A label")

        # image = Gtk.Image.new_from_icon_name("help-about", Gtk.IconSize.MENU)
        # image.set_pixel_size(256)
        # stack.add_titled(image, "image", "Image")


        stacksidebar = Gtk.StackSidebar()
        stacksidebar.set_stack(stack)
        self.hbox.add(stacksidebar)
        self.hbox.add(stack)

        self.loadcss()


    def loadcss(self):
        strcss="""
        #Mainform__ {
            background-color: #eef;
        }

        .unused {
            color: #F55;
            background-color: #eef;
            /* 测试 */
        }
        """
        # strpath="/tmp/wbtools.css"
        # fp = open(strpath, 'w')
        # fp.write(strcss)
        # fp.close()

        provider = Gtk.CssProvider()
        provider.load_from_data(strcss)
        # provider.connect("parsing-error", self.show_css_parsing_error)
        # fname = Gio.file_new_for_path('play.css')
        # provider.load_from_file(fname)
        # https://docs.gtk.org/gtk4/method.CssProvider.load_from_file.html
        # provider.load_from_data(strcss), load_from_path, load_from_file, load_from_string
        # provider.load_from_path(strpath)
        # button.set_name("btnFillpwd")
        # self.apply_css(window, provider)
        self.apply_css(self, provider)

    def apply_css(self, widget, provider):
        Gtk.StyleContext.add_provider(widget.get_style_context(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        if isinstance(widget, Gtk.Container):
            widget.forall(self.apply_css, provider)

    def showmessage(self, strtitle, strmessage):
        # Gtk.MessageType.ERROR
        # Gtk.MessageType.INFO  # https://qytz-notes.readthedocs.io/tech/PyGObject-Tutorial/dialogs.html
        dialog = Gtk.MessageDialog(
                transient_for=self,
                # flags=Gtk.DialogFlags.MODAL,
                modal=True,
                message_type=Gtk.MessageType.INFO,
                buttons=Gtk.ButtonsType.CANCEL,
                text=strtitle,
        )
        dialog.format_secondary_text(strmessage)
        btn = dialog.get_widget_for_response(Gtk.ResponseType.CANCEL)
        btn.set_label("好的")
        dialog.run()
        dialog.destroy()

if __name__ == '__main__':
    # 获取脚本所在目录的路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # 更改工作目录为脚本所在目录
    os.chdir(script_dir)

    win = Mainform()
    win.connect("destroy",Gtk.main_quit)
    win.show_all()
    exit(Gtk.main())

